//
//  RejectViewController.swift
//  ShareCar
//
//  Created by jiuzhongkeji on 2019/2/20.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit
import AipOcrSdk
class RejectViewController: UIViewController {
    
    private var data: User.RejectDetail?
    @IBOutlet weak var reasonLabel: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
    
    /// 当前正在上传的驳回项索引
    var resonOption: Int!
    /// 构建提交的参数信息
    var list = [[String: Any]]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        JZLoading.showLoadingWith(toView: view)
        User.rejectAttestation(success: { [weak self] data in
            JZLoading.hideLoading()
            if let self = self, let reason = data?.rejectReason {
                self.data = data
                self.reasonLabel.text = "驳回原因:\(reason)"
                self.collectionView.reloadData()
            }
        }) { [weak self] error in
            JZLoading.hideLoading()
            self?.showError(error.msg)
        }
        // Do any additional setup after loading the view.
    }
    
    @IBAction func backRoot(_ sender: UIBarButtonItem) {
        navigationController?.popToRootViewController(animated: true)
    }
    
    @IBAction func handle(_ sender: Any) {
        JZLoading.showLoadingWith(toView: self.view)
        User.commitReject(rejectInfo: self.list, success: {
            JZLoading.hideLoading()
            self.showError("提交成功")
            self.navigationController?.popToRootViewController(animated: true)
            
        }) { error in
            JZLoading.hideLoading()
            self.showError(error.msg)
        }
    }
    
    @IBAction func goback(_ sender: Any) {
        self.navigationController?.popToRootViewController(animated: true)
    }
    //网络图片
    func webImageOCR() {
        let vc = AipGeneralVC.viewController { [weak self] image in
            self?.dismiss(animated: true, completion: nil)
            self?.uploadImage(image: image)

        }
        present(vc!, animated: true, completion: nil)
    }
    
    func uploadImage(image:UIImage?) {
        guard let image = image else {
            XHProgressHUD.showError("图片为空")
            return
        }
        
        DispatchQueue.global().async { [weak self] in
            if let self = self {
                let imgData = image.compress(maxSizeKBytes: kMaxSizeKBytes)
                DispatchQueue.main.async {
                    let file = HTTPRequest.File(data: imgData, name: "image_path", fileName: "file.jpg", mimeType: "image/jpg")
                    
                    JZLoading.showLoadingWith(toView: self.view)
                    File.upload(file: file, success: { [weak self] data in
                        JZLoading.hideLoading()
                        
                        if let data = data, let self = self, let value = self.resonOption {
                            
                            let obj = ["reject_option":value,
                                       "reject_option_image":data.imagePath] as [String : Any]
                            
                            self.list.append(obj)
                            //图片赋值
                            let cell = self.collectionView.cellForItem(at: IndexPath(row: self.resonOption - 1, section: 0)) as! RejectReasonCell
                            cell.backgroundButton.setBackgroundImage(image, for: .normal)
                        }
                        
                    }) { error in
                        JZLoading.hideLoading()
                        self.showError(error)
                    }
                    self.dismiss(animated: true)
                }
            }
        }
    }


    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension RejectViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data?.rejectOptionList.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RejectReasonCell
        if let model = data?.rejectOptionList[indexPath.row] {
            cell.model = model
            cell.block = { [weak self] in
                if let self = self {
                self.resonOption = model.rejectOption
                for (ind, obj) in self.list.enumerated() {
                    if let index = obj["reject_option"] as? Int, index == self.resonOption {
                        self.list.remove(at: ind)
                    }
                }
                self.webImageOCR()
                }
            }
        }
        return cell
    }
    
    
}
